/**
 * Title: jFamilyTree
 * Description: jFamilyTree
 * About: Designed and rewritten by Andreas Lundgren, based on the Treebolic application suite
 * Copyright: (c) 2001-2008
 * Terms of use: see license agreement at http://treebolic.sourceforge.net/en/license.htm
 * Author: Bernard Bou
 * Company: bsys
 */
package jFamilyTree.provider.xml.graph;

import java.net.URL;

import jFamilyTree.model.IProvider;
import jFamilyTree.model.IProviderContext;
import jFamilyTree.model.Model;
import jFamilyTree.model.Tree;

/**
 * Graph provider
 * 
 * @author Bernard Bou
 */
public abstract class AbstractProvider implements IProvider
{
	// D A T A
	
	/**
	 * Provider client
	 */
	protected IProviderContext theContext;
	
	// C O N S T R U C T O R

	/**
	 * Constructor
	 */
	public AbstractProvider()
	{
	}

	// A B S T R A C T . M E T H O D S
	
	/**
	 * Fallback hook to determine source
	 * 
	 * @param thisSource
	 *        passed source
	 * @return source
	 */
	abstract public String getSource(String thisSource);

	/**
	 * Get parser
	 *
	 * @return abstract parser
	 */
	abstract public AbstractParser getParser();

	// P R O V I D E R  .  I N T E R F A C E
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see jFamilyTree.model.IProvider#set(jFamilyTree.model.IProviderContext)
	 */
	public void connect(IProviderContext thisContext)
	{
		theContext = thisContext;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see jFamilyTree.model.IProvider#makeModel(java.lang.String)
	 */
	public Model makeModel(String thatSource)
	{
		// get source
		String thisSource = getSource(thatSource);

		// parse source
		if (thisSource != null)
		{
			// URL
			URL thisUrl = theContext.makeURL(thisSource);
			if (thisUrl != null)
			{
				// parse
				theContext.putProgress("Loading ..." + thisSource, false);
				Model thisModel = getParser().parseModel(thisUrl);
				if (thisModel != null)
				{
					theContext.putProgress("Loaded " + thisSource, false);
					return thisModel;
				}
				theContext.putMessage("Cannot load " + thisSource);
			}
			else
				theContext.putMessage("Bad URL " + thisSource);
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see jFamilyTree.model.IProvider#makeTree(java.lang.String, boolean)
	 */
	public Tree makeTree(String thatSource, boolean checkRecursion)
	{
		// get source
		String thisSource = getSource(thatSource);

		// parse XML file
		if (thisSource != null)
		{
			// URL
			URL thisUrl = theContext.makeURL(thisSource);
			if (thisUrl != null)
			{
				// parse
				theContext.putProgress("Loading ..." + thisSource, false);
				Tree thisTree = getParser().parseTree(thisUrl);
				if (thisTree != null)
				{
					theContext.putProgress("Loaded " + thisSource, false);
					return thisTree;
				}
				theContext.putMessage("Cannot load" + thisSource);
			}
			else
				theContext.putMessage("Bad URL " + thisSource);
		}
		return null;
	}
}
